package com.mj.guoqi.dao;

import java.util.ArrayList;
import java.util.List;

import com.mj.guoqi.bean.GuoqiDto;
import com.mj.guoqi.bean.GuoqiList;
import com.mj.guoqi.util.DBHelper;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * 国旗查询dao
 * @author zhaominglei
 * @date 2015-8-15
 * 
 */
public class GuoqiDao extends BaseDao {
	private static final String TABLE_NAME = "guoqi";
	
	public int getCount(Context context) {
		return getCount(context, TABLE_NAME);
	}

	public void deleteAll(Context context) {
		deleteAll(context, TABLE_NAME);
	}
	
	public GuoqiList getPagination(Context context, String selection, String[] selectionArgs, String orderBy, int currentPage, int pageSize) {
		GuoqiList guoqiList = new GuoqiList();
		SQLiteDatabase db = DBHelper.getInstance(context).getReadableDatabase();
		Cursor cursor = db.query(TABLE_NAME, null, selection, selectionArgs, null, null, orderBy, (currentPage - 1) * pageSize+","+pageSize);
		List<GuoqiDto> recordList = new ArrayList<GuoqiDto>();
		while (cursor.moveToNext()) {
			GuoqiDto guoqiDto = new GuoqiDto();
			guoqiDto.setGuoqiId(cursor.getLong(cursor.getColumnIndex("guoqiId")));
			guoqiDto.setName(cursor.getString(cursor.getColumnIndex("name")));
			guoqiDto.setLogo(cursor.getString(cursor.getColumnIndex("logo")));
			guoqiDto.setIntroduction(cursor.getString(cursor.getColumnIndex("introduction")));
			recordList.add(guoqiDto);
		}
		
		int recordCount = getCount(context);
        int currPage = currentPage;
        if(currentPage < 1) {
            currentPage = 1;
        }
        boolean hasPrePage = false;
        //上一页等于当前页减一
        int prePage = currPage - 1;
        if(prePage < 1) {
            hasPrePage = false;//没有上一页
            prePage = 1;
        }else {
            hasPrePage = true;//有上一页
        }
        //计算总页数
        int pageCount = (int)Math.ceil(recordCount / (double)pageSize);
        if(currPage > pageCount) {
        	currPage = pageCount;
        }
        boolean hasNextPage = false;
        //下一页等于当前页加一
        int nextPage = currPage + 1;
        if(nextPage > pageCount) {
        	hasNextPage = false;//没有下一页
            nextPage = pageCount;
        }else {
        	hasNextPage = true;//有下一页
        }
        
        guoqiList.setRecordCount(recordCount);
		guoqiList.setPageSize(pageSize);
        guoqiList.setCurrentPage(currPage);
        guoqiList.setHasNextPage(hasNextPage);
        guoqiList.setHasPrePage(hasPrePage);
        guoqiList.setNextPage(nextPage);
        guoqiList.setPageCount(pageCount);
        guoqiList.setPrePage(prePage);
		guoqiList.setRecordList(recordList);
		cursor.close();
//		if (!cursor.isClosed()) {
//			cursor.close();
//		}
//		db.close();
		return guoqiList;
	}
}	
